package org.springframework.boot.autoconfigure.data.redis;

import org.springframework.data.redis.connection.lettuce.ExtendLettuceConnectionFactory;
import com.jlf.cache.redis.reactive.property.RedisExtendProperties;
import io.lettuce.core.resource.ClientResources;
import org.joor.Reflect;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.ssl.SslBundles;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;

/**
 * 扩展的链接配置
 *
 * @author wujr
 * 2023/8/7
 * @version 1.0
 * 【变更历史】
 * [wujr 2023/8/7 1.0 新增]
 */
public class ExtendLettuceConnectionConfiguration extends LettuceConnectionConfiguration{

    public ExtendLettuceConnectionConfiguration(RedisExtendProperties properties, ObjectProvider<RedisStandaloneConfiguration> standaloneConfigurationProvider, ObjectProvider<RedisSentinelConfiguration> sentinelConfigurationProvider, ObjectProvider<RedisClusterConfiguration> clusterConfigurationProvider, RedisConnectionDetails connectionDetails, ObjectProvider<SslBundles> sslBundles) {
        super(properties, standaloneConfigurationProvider, sentinelConfigurationProvider, clusterConfigurationProvider, connectionDetails, sslBundles);
    }

    public RedisExtendProperties properties(){
        return (RedisExtendProperties)super.getProperties();
    }

    public ExtendLettuceConnectionFactory factory(
            ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers,
            ClientResources clientResources){
        LettuceClientConfiguration clientConfig = Reflect.on(this).call("getLettuceClientConfiguration",
                builderCustomizers,
                clientResources,
                getProperties().getLettuce().getPool()).get();
//        LettuceClientConfiguration clientConfig = super.getLettuceClientConfiguration(builderCustomizers, clientResources,
//                getProperties().getLettuce().getPool());
        return createLettuceConnectionFactory(clientConfig);
//        return super.redisConnectionFactory(builderCustomizers, clientResources);
    }
    private ExtendLettuceConnectionFactory createLettuceConnectionFactory(LettuceClientConfiguration clientConfiguration) {
        if (getSentinelConfig() != null) {
            return new ExtendLettuceConnectionFactory(super.getSentinelConfig(), clientConfiguration);
        }
        if (getClusterConfiguration() != null) {
            return new ExtendLettuceConnectionFactory(getClusterConfiguration(), clientConfiguration);
        }
        return new ExtendLettuceConnectionFactory(getStandaloneConfig(), clientConfiguration);
    }
}
